package middleware

import (
	"stacks/config"
	"stacks/utils"
	"strings"

	"github.com/gin-gonic/gin"
)

// JWTAuth JWT认证中间件
func JWTAuth(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取Authorization header
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			utils.Unauthorized(c, "缺少认证Token")
			c.Abort()
			return
		}

		// 检查Bearer格式
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			utils.Unauthorized(c, "Token格式错误")
			c.Abort()
			return
		}

		tokenString := parts[1]

		// 解析Token
		claims, err := utils.ParseToken(tokenString, cfg.JWT.Secret)
		if err != nil {
			utils.Unauthorized(c, "Token无效或已过期")
			c.Abort()
			return
		}

		// 将用户信息存入上下文
		c.Set("userId", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("tenantId", claims.TenantID)

		c.Next()
	}
}

// GetUserInfo 从上下文中获取用户信息
func GetUserInfo(c *gin.Context) (userID uint, username string, tenantID uint) {
	if val, exists := c.Get("userId"); exists {
		userID = val.(uint)
	}
	if val, exists := c.Get("username"); exists {
		username = val.(string)
	}
	if val, exists := c.Get("tenantId"); exists {
		tenantID = val.(uint)
	}
	return
}
